package com.woniuxy.exam.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.woniuxy.commons.entity.TrueOrFalse;
import com.woniuxy.exam.service.TrueOrFalseService;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zouyang
 * @date 2020/7/21 - 16:03
 */
public class TOFListener extends AnalysisEventListener<TrueOrFalse> {

    private static final int BATCH_COUNT = 20;
    List<TrueOrFalse> list = new ArrayList<>();

    private TrueOrFalseService trueOrFalseService;
    public TOFListener(TrueOrFalseService trueOrFalseService){
        this.trueOrFalseService = trueOrFalseService;
    }

    @Override
    public void invoke(TrueOrFalse trueOrFalse, AnalysisContext context) {
        list.add(trueOrFalse);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if(list==null){
            return;
        }
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            list.clear();
        }
    }

    private void saveData() {
        trueOrFalseService.insertList(list);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if(list.isEmpty()==false){
            saveData();
        }
        list.clear();
        list=null;
    }
}
